package com.cookie.meetproject.fragment;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cookie.framework.adapter.CommonAdapter;
import com.cookie.framework.adapter.CommonViewHolder;
import com.cookie.framework.base.BaseFragment;
import com.cookie.framework.bmob.BmobManger;
import com.cookie.framework.bmob.IMUser;
import com.cookie.framework.bmob.SquareSet;
import com.cookie.framework.helper.FileHelper;
import com.cookie.framework.helper.WindowHelper;
import com.cookie.framework.manager.MediaPlayerManager;
import com.cookie.framework.utils.AnimUtils;
import com.cookie.framework.utils.CommonUtils;
import com.cookie.framework.utils.TimeUtils;
import com.cookie.framework.view.VideoJzvdStd;
import com.cookie.meetproject.R;
import com.cookie.meetproject.ui.ImagePreviewActivity;
import com.cookie.meetproject.ui.PushSquareActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 项目名:    MeetProject
 * 包名:      com.cookie.meetproject.fragment
 * 文件名:    SquareFragment
 * 创建者:    cookie
 * 创建时间:   2020/1/5 0:41
 * 描述:      广场
 */

public class SquareFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {

    /**
     * 1、设计数据库
     * 2、实现我们的媒体发送
     * 3、实现列表、并且实现我们的文本和图片的发送
     */

    private static final int REQUEST_CODE = 1000;

    private ImageView iv_push;
    private RecyclerView mSquareView;
    private SwipeRefreshLayout mSquareSwipeLayout;
    private FloatingActionButton fb_squaue_top;
    private View item_empty_view;

    private List<SquareSet> mList = new ArrayList<>();
    private CommonAdapter<SquareSet> mSquareAdapter;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //播放类
    private MediaPlayerManager mMusicManager;
    //音乐是否在播放
    private boolean isMusicPlay = false;

    private WindowManager.LayoutParams lpMusicParams;
    private View musicWindowView;

    private CircleImageView ivMusicPhoto;
    private ProgressBar pbMusicPos;
    private TextView tvMusicCur;
    private TextView tvMusicAll;

    private ObjectAnimator objAnimMusic;

    private static final int UPDATE_POS = 1235;
    //是否移动
    private boolean isMove = false;
    //是否拖拽
    private boolean isDrag = false;

    private int mLastX;
    private int mLastY;

    private String path ="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1590876140006&di=2e327abdc946da65f67e2051df1ded7d&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fw%3D580%2Fsign%3Dc9028de9b551f819f1250342eab54a76%2Fabfc9e3df8dcd1004ab1f3e3778b4710b8122ffa.jpg";

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_POS:
                    int pos = msg.arg1;
                    tvMusicCur.setText(TimeUtils.formatDuring(pos));
                    pbMusicPos.setProgress(pos);
                    break;
            }
            return false;
        }
    });

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_square, null);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mMusicManager = new MediaPlayerManager();
        mMusicManager.setOnComplteionListener(mp -> {
            isMusicPlay = false;
        });

        mMusicManager.setOnProgressListener(new MediaPlayerManager.OnMusicProgressListener() {
            @Override
            public void onProgress(int progress, int pos) {
                Message message = new Message();
                message.what = UPDATE_POS;
                message.arg1 = progress;
                mHandler.sendMessage(message);
            }
        });

        initMusicWindow();

        iv_push = view.findViewById(R.id.iv_push);
        mSquareView = view.findViewById(R.id.mSquareView);
        mSquareSwipeLayout = view.findViewById(R.id.mSquareSwipeLayout);
        item_empty_view = view.findViewById(R.id.item_empty_view);

        iv_push.setOnClickListener(this);
        mSquareSwipeLayout.setOnRefreshListener(this);

        mSquareView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mSquareView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mSquareAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<SquareSet>() {
            @Override
            public void onBindViewHolder(SquareSet model, CommonViewHolder holder, int type, int position) {
                //加载个人信息
                loadMeInfo(model.getUserId(), holder);
                //设置时间
                holder.setText(R.id.tv_time, dateFormat.format(model.getPushTime()));

                if (!TextUtils.isEmpty(model.getText())) {
                    holder.setText(R.id.tv_text, model.getText());
                } else {
                    holder.getView(R.id.tv_text).setVisibility(View.GONE);
                }

                //多媒体
                switch (model.getPushType()) {
                    case SquareSet.PUSH_TEXT:
                        goneItemView(holder, false, false, false);
                        break;
                    case SquareSet.PUSH_IMAGE:
                        goneItemView(holder, true, false, false);
                        holder.setImageUrl(getActivity(), R.id.iv_img, path);
                        holder.getView(R.id.iv_img).setOnClickListener(v -> {
                            ImagePreviewActivity.startActivity(getActivity(), true, model.getMediaUrl());
                        });
                        break;
                    case SquareSet.PUSH_MUSIC:
                        goneItemView(holder, false, true, false);
                        holder.getView(R.id.ll_music).setOnClickListener(v -> {
                            //播放音乐
                            if (mMusicManager.isPlaying()) {
                                hideMusicWindow();
                            } else {
                                if (isMusicPlay) {
                                    mMusicManager.continuePlay();
                                } else {
                                    AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.guide);
                                    mMusicManager.startPlay(file);
                                    isMusicPlay = true;
                                }
                                showMusicWindow();
                            }
                        });
                        break;
                    case SquareSet.PUSH_VIDEO:
                        goneItemView(holder, false, false, true);
                        holder.getView(R.id.tv_text).setVisibility(View.GONE);
                        VideoJzvdStd jzvdStd = holder.getView(R.id.jz_video);
                        jzvdStd.setUp("http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4"
                                , model.getText());
                        jzvdStd.thumbImageView.setImageResource(R.drawable.img_flashlight_p);
                        Observable.create(new ObservableOnSubscribe<Bitmap>() {

                            @Override
                            public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
                                emitter.onNext(FileHelper.getInstance().getNetVideoBitmap(model.getMediaUrl()));
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<Bitmap>() {
                                    @Override
                                    public void accept(Bitmap bitmap) throws Exception {
                                        if (bitmap != null) {
                                            jzvdStd.thumbImageView.setImageBitmap(bitmap);
                                        }
                                    }
                                });
                        break;
                }
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_square_item;
            }
        });
        mSquareView.setAdapter(mSquareAdapter);
        loadSquare();
    }

    //初始化音乐悬浮窗
    private void initMusicWindow() {
        lpMusicParams = WindowHelper.getInstance().createLayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Gravity.TOP | Gravity.LEFT
        );
        musicWindowView = WindowHelper.getInstance().getView(R.layout.layout_square_music_item);
        //初始化view
        ivMusicPhoto = musicWindowView.findViewById(R.id.iv_music_photo);
        pbMusicPos = musicWindowView.findViewById(R.id.pb_music_pos);
        tvMusicCur = musicWindowView.findViewById(R.id.tv_music_cur);
        tvMusicAll = musicWindowView.findViewById(R.id.tv_music_all);

        objAnimMusic = AnimUtils.rotation(ivMusicPhoto);
        musicWindowView.setOnClickListener(v -> {
            hideMusicWindow();
        });

        musicWindowView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int mStartX = (int) event.getRawX();
                int mStartY = (int) event.getRawY();

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isMove = false;
                        isDrag = false;

                        mLastX = (int) event.getRawX();
                        mLastY = (int) event.getRawY();

                        break;
                    case MotionEvent.ACTION_MOVE:
                        //偏移量
                        int dx = mStartX - mLastX;
                        int dy = mStartY - mLastY;

                        if (isMove) {
                            isDrag = true;
                        } else {
                            if (dx == 0 && dy == 0) {
                                isMove = false;
                            } else {
                                isMove = true;
                                isDrag = true;
                            }
                        }
                        //移动
                        lpMusicParams.x += dx;
                        lpMusicParams.y += dy;

                        //重置坐标
                        mLastX = mStartX;
                        mLastY = mStartY;
                        WindowHelper.getInstance().updateView(musicWindowView, lpMusicParams);
                        break;
                }
                return isDrag;
            }
        });
    }

    //显示窗口
    private void showMusicWindow() {
        pbMusicPos.setMax(mMusicManager.getDuration());
        tvMusicAll.setText(TimeUtils.formatDuring(mMusicManager.getDuration()));
        objAnimMusic.start();
        WindowHelper.getInstance().showView(musicWindowView, lpMusicParams);
    }

    //隐藏窗口
    private void hideMusicWindow() {
        mMusicManager.pausePlay();
        objAnimMusic.pause();
        WindowHelper.getInstance().hideView(musicWindowView);
    }

    //隐藏view
    private void goneItemView(CommonViewHolder holder, boolean img, boolean audio, boolean video) {
        holder.getView(R.id.iv_img).setVisibility(img ? View.VISIBLE : View.GONE);
        holder.getView(R.id.ll_music).setVisibility(audio ? View.VISIBLE : View.GONE);
        holder.getView(R.id.ll_video).setVisibility(video ? View.VISIBLE : View.GONE);
    }

    //加载个人信息
    private void loadMeInfo(String userId, CommonViewHolder holder) {
        BmobManger.getInstance().queryObjectIdUser(userId, new FindListener<IMUser>() {
            @Override
            public void done(List<IMUser> list, BmobException e) {
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {
                        IMUser imUser = list.get(0);
                        holder.setImageUrl(getActivity(), R.id.iv_photo, path);
                        holder.setText(R.id.tv_nickname, imUser.getNickName());
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_push:
                Intent intent = new Intent(getActivity(), PushSquareActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                //刷新
                loadSquare();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //加载数据
    private void loadSquare() {
        mSquareSwipeLayout.setRefreshing(true);
        BmobManger.getInstance().queryAllSquare(new FindListener<SquareSet>() {
            @Override
            public void done(List<SquareSet> list, BmobException e) {
                mSquareSwipeLayout.setRefreshing(false);
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {
                        //倒叙
                        Collections.reverse(list);
                        mSquareView.setVisibility(View.VISIBLE);
                        item_empty_view.setVisibility(View.GONE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(list);
                        mSquareAdapter.notifyDataSetChanged();
                    } else {
                        mSquareView.setVisibility(View.GONE);
                        item_empty_view.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        loadSquare();
    }
}
